package com.tensquare.common.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: WangYaWei
 * @description:
 * @create: 2019-08-27 14:01
 **/
@Slf4j
@Component
public class SecurityUtils {

    @Autowired
    @Qualifier("commonJwtUtil")
    private JwtUtil jwtUtil;

    /**
     * 获取当前登录用户id
     * @return
     */
    public String getCuurentUserid(){
        Claims claims = getCuurentClaims();
        return claims.getId();
    }

    /**
     * 获取当前登录用户Claims
     * @return
     */
    public Claims getCuurentClaims(){
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authorization = req.getHeader("Authorization");
        if(authorization != null && !"".equals(authorization.trim())){
            String token = authorization.substring(7);
            Claims claims = null;
            try {
                claims = jwtUtil.parseJwt(token);
            } catch (ExpiredJwtException e){
                return e.getClaims();
            } catch (Exception e){
                e.printStackTrace();
            }


            return claims;

        }
        return null;
    }
}
